﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class UserControls_CarbonFootprintQuestion_Water_WaterFootprint : CarbonExchange.WebControls.AuditQuestionBase
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        rblBills.SelectedIndexChanged += new EventHandler(rblBills_SelectedIndexChanged);
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public override void DataBind()
    {
        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("rblBills")))
            rblBills.Text = Answer.GetSetting<string>("rblBills");
        rblBills_SelectedIndexChanged(rblBills, EventArgs.Empty);

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("ddlPeriod")))
            ddlPeriod.Text = Answer.GetSetting<string>("ddlPeriod");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("txtValue")))
            txtValue.Text = Answer.GetSetting<string>("txtValue");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("ddlValue")))
            ddlValue.Text = Answer.GetSetting<string>("ddlValue");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("txtWashingMachine")))
            txtWashingMachine.Text = Answer.GetSetting<string>("txtWashingMachine");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("txtDishwasher")))
            txtDishwasher.Text = Answer.GetSetting<string>("txtDishwasher");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("txtBaths")))
            txtBaths.Text = Answer.GetSetting<string>("txtBaths");

        if (!string.IsNullOrEmpty(Answer.GetSetting<string>("txtShowers")))
            txtShowers.Text = Answer.GetSetting<string>("txtShowers");
        
        base.DataBind();
    }

    protected override bool SaveQuestion()
    {
        var completed = true;

        var profileItemFactory = new CarbonExchange.Bll.AmeeProfileItemFactory();
        var dataCategoryFactory = new CarbonExchange.Bll.AmeeDataCatagoryFactory();
        var itemsToKeep = new List<CarbonExchange.Bll.AnswerItem>();
        
        Answer.SetSetting<string>("rblBills", rblBills.Text);
        if (rblBills.Text == "1")
        {
            if (!SaveAmount(profileItemFactory, dataCategoryFactory, itemsToKeep))
            {
                completed = false;
            }
        }
        else if (rblBills.Text == "0")
        {
            if (!SaveEstimate(profileItemFactory, dataCategoryFactory, itemsToKeep))
            {
                completed = false;
            }
        }
        else
        {
            completed = false;
        }

        var deleteItems = Answer.AnswerItems.Where(x => !itemsToKeep.Contains(x)).ToList();

        if (deleteItems.Count > 0)
        {
            CarbonExchange.Bll.AnswerItemFactory answerItemFactory = new CarbonExchange.Bll.AnswerItemFactory();
            answerItemFactory.Delete(deleteItems);
            foreach (var del in deleteItems)
            {
                if (Answer.AnswerItems.Contains(del))
                    Answer.AnswerItems.Remove(del);
            }
        }
        return completed;
    }

    private bool SaveEstimate(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        Answer.SetSetting<string>("txtWashingMachine", txtWashingMachine.Text);
        Answer.SetSetting<string>("txtDishwasher", txtDishwasher.Text);
        Answer.SetSetting<string>("txtBaths", txtBaths.Text);
        Answer.SetSetting<string>("txtShowers", txtShowers.Text);

        var completed = true;

        if (!SaveEstimateItem("Washing Machine", "type=washing machine", txtWashingMachine.Text, null, profileItemFactory, dataCategoryFactory, itemsToKeep))
            completed = false;
        if (!SaveEstimateItem("Dishwasher", "type=dishwasher", txtDishwasher.Text, null, profileItemFactory, dataCategoryFactory, itemsToKeep))
            completed = false;
        if (!SaveEstimateItem("Baths", "type=bath", txtBaths.Text, null, profileItemFactory, dataCategoryFactory, itemsToKeep))
            completed = false;
        if (!SaveEstimateItem("Showers", "type=shower", txtShowers.Text, null, profileItemFactory, dataCategoryFactory, itemsToKeep))
            completed = false;
        SaveEstimateItem("ToiletFlushes", "type=toilet flushing", (4.8 * 7 * Audit.PeopleInHousehold).ToString(), null, profileItemFactory, dataCategoryFactory, itemsToKeep);
        SaveEstimateItem("Taps", "type=sink taps", null, (3.5275 * 7 * Audit.PeopleInHousehold).ToString(), profileItemFactory, dataCategoryFactory, itemsToKeep);
        return completed;
    }

    private bool SaveEstimateItem(string name, string choice, string usesPerWeek, string minutesPerWeek, CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        decimal? tmpUses = null;
        if (!string.IsNullOrEmpty(usesPerWeek))
        {
            try
            {
                tmpUses = decimal.Parse(usesPerWeek);
            }
            catch (FormatException) { }
        }
        decimal? tmpMin = null;
        if (!string.IsNullOrEmpty(minutesPerWeek))
        {
            try
            {
                tmpMin = decimal.Parse(minutesPerWeek);
            }
            catch (FormatException) { }
        }
        //convert week to days
        tmpUses = tmpUses / 7;
        tmpMin = tmpMin / 7;

        var tmpProfileItem = EnsureProfileItem(name, profileItemFactory, dataCategoryFactory, "/home/water/Usage", choice);
        var save = string.IsNullOrEmpty(tmpProfileItem.Id);

        if (tmpProfileItem.GetValue<decimal?>("usesPerDay") != tmpUses)
        {
            tmpProfileItem.SetValue<decimal?>("usesPerDay", tmpUses);
            save = true;
        }

        if (tmpProfileItem.GetValue<decimal?>("minutesPerDay") != tmpMin)
        {
            tmpProfileItem.SetValue<decimal?>("minutesPerDay", tmpMin);
            save = true;
        }

        if (save)
        {
            profileItemFactory.Save(tmpProfileItem);
        }

        itemsToKeep.Add(Answer.SetItem(name, tmpProfileItem));
        return tmpUses.HasValue || tmpMin.HasValue;
    }

    private bool SaveAmount(CarbonExchange.Bll.AmeeProfileItemFactory profileItemFactory, CarbonExchange.Bll.AmeeDataCatagoryFactory dataCategoryFactory, List<CarbonExchange.Bll.AnswerItem> itemsToKeep)
    {
        Answer.SetSetting<string>("ddlPeriod", ddlPeriod.Text);
        Answer.SetSetting<string>("txtValue", txtValue.Text);
        Answer.SetSetting<string>("ddlValue", ddlValue.Text);

        decimal amount = 0;
        try
        {
            amount = decimal.Parse(txtValue.Text);
        }
        catch (FormatException) { }

        int period = 1;
        try
        {
            period = int.Parse(ddlPeriod.Text);
        }
        catch (FormatException) { }

        amount = amount / period;

        if (ddlValue.Text == "ft")
        {
            //convert ft3 to m3
            amount = amount * 0.02831m;
        }
        //convert m3 to lt3
        amount = amount * 1000m;

        var tmpProfileItem = EnsureProfileItem("WaterBills", profileItemFactory, dataCategoryFactory, "/home/water", "type=cold");

        var save = string.IsNullOrEmpty(tmpProfileItem.Id);

        if (tmpProfileItem.GetValue<decimal>("litresPerMonth") != amount)
        {
            tmpProfileItem.SetValue<decimal>("litresPerMonth", amount);
            save = true;
        }

        if (save)
        {
            profileItemFactory.Save(tmpProfileItem);
        }

        itemsToKeep.Add(Answer.SetItem("WaterBills", tmpProfileItem));

        return amount > 0;
    }


    void rblBills_SelectedIndexChanged(object sender, EventArgs e)
    {
        phAmount.Visible = rblBills.Text == "1";
        phEstimate.Visible = rblBills.Text == "0";
    }

    public override int GetActiveItemsCount()
    {
        if (phAmount.Visible)
        {
            return phAmount.Controls.OfType<Panel>().Count() + 1;
        }
        else if (phEstimate.Visible)
        {
            return phEstimate.Controls.OfType<Panel>().Count() + 1;
        }
        else
        {
            return 1;
        }

    }

    public override int RenderItems(int start, int end, HtmlTextWriter writer)
    {
        var items = new List<Panel>();
        items.Add(pnlBills);
        if (phAmount.Visible)
        {
            items.AddRange(phAmount.Controls.OfType<Panel>());
        }
        else if (phEstimate.Visible)
        {
            items.AddRange(phEstimate.Controls.OfType<Panel>());
        }
        int i = 0;
        foreach (var panel in items.Skip(start).Take(end - start))
        {
            panel.RenderControl(writer);
            i++;
        }
        return i;
    }
}

